package cn.smdq.ch.gateway.core.provider;

import cn.smdq.ch.common.constant.SecurityConstants;
import cn.smdq.ch.gateway.core.route.ZuulRouteLocator;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.util.CollectionUtils.isEmpty;

/**
 * @author shuimodanqing
 * create at:  2019/1/28  3:37 PM
 * @description 配置swagger资源
 */
@Component
@Primary
@SuppressWarnings("all")
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {

    private ZuulRouteLocator routeLocator;

    public GatewaySwaggerResourcesProvider(ZuulRouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> swaggerResourceList = new ArrayList<>();
        List<Route> zuulRouteList = routeLocator.getRoutes();
        if (!isEmpty(zuulRouteList)) {
            zuulRouteList.forEach(route -> {
                System.out.println("routeId: " + route.getId() + " 《=====》 fullPath: " + route.getFullPath());
                if (!SecurityConstants.AUTH_SERVER_ID.equalsIgnoreCase(route.getId())) {
                    swaggerResourceList.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")));
                }
            });
        }
        return swaggerResourceList;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource resource = new SwaggerResource();
        resource.setName(name);
        resource.setLocation(location);
        resource.setSwaggerVersion("2.0");
        WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter
        return resource;
    }
}
